package com.ply.flashsalessystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ply.flashsalessystem.annotation.AuthorityName;
import com.ply.flashsalessystem.annotation.UserAuthority;
import com.ply.flashsalessystem.entity.pojo.OrderForGoods;
import com.ply.flashsalessystem.entity.pojo.OrderForGoodsDetaile;
import com.ply.flashsalessystem.entity.pojo.ShopCar;
import com.ply.flashsalessystem.entity.pojo.Store;
import com.ply.flashsalessystem.entity.result.Result;
import com.ply.flashsalessystem.entity.status.OrderDetailsStatus;
import com.ply.flashsalessystem.entity.status.OrderStatus;
import com.ply.flashsalessystem.entity.vo.OrderForGoodsDetaileVo;
import com.ply.flashsalessystem.entity.vo.store.OrderForStoreVo;
import com.ply.flashsalessystem.entity.wrapper.WrapperOrder;
import com.ply.flashsalessystem.service.*;
import com.ply.flashsalessystem.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author XiaoPan
 * @since 2022-03-23
 */
@RestController
@RequestMapping("order")
@Api("订单接口")
@CrossOrigin
public class OrderForGoodsController {
    @Autowired
    OrderForGoodsService orderForGoodsService;

    @Autowired
    UserService userService;

    @Autowired
    OrderForGoodsDetaileService orderForGoodsDetaileService;

    @Autowired
    ShopCarService shopCarService;

    @Autowired
    StoreService storeService;

    /*
    增加订单
     */
//    @AuthorityName(authorityId = 17, authorityName = "用户 下订单(清空购物车)")
    @UserAuthority
    @ApiOperation("用户 下订单(清空购物车)")
    @PostMapping("user/createOrderClear/{storeId}")
    @Transactional
    public Result createOrderClear(@PathVariable("storeId") long storeId) {
        if (storeId < 0) {
            return Result.error().message("参数错误");
        }

        //查询店家地址
        Store byId1 = storeService.getById(storeId);
        if (byId1 == null) {
            return Result.error().message("店家id 不存在 或 已退出");
        }
        QueryWrapper<ShopCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", UserUtils.getUserId());
        List<ShopCar> list = shopCarService.list(queryWrapper);

        return userService.createOrder(storeId, list)
                ? Result.ok().message("创建订单成功")
                : Result.error().message("创建订单失败");
    }

//    @AuthorityName(authorityId = 18, authorityName = "用户 下订单(选择部分购物车)")
    //生成订单  由  传进来  list 购物车id  或者 商品id 和 数量
    @UserAuthority
    @ApiOperation("用户 将购物车中的 物品清空 下订单(部分购物车)")
    @PostMapping("user/createOrder/{storeId}")
    @Transactional
    public Result createOrder(@PathVariable("storeId") Long storeId,
                              @RequestBody List<Integer> shopCarIdList) {
        // 购物车 id 可以写成 封装成对象 或者 对string 自己处理

        //查询店家地址
        Store byId1 = storeService.getById(storeId);
        if (byId1 == null) {
            return Result.error().message("店家id 不存在 或 已退出");
        }

        List<ShopCar> shopCars = shopCarService.listByIds(shopCarIdList);
        if (shopCars.isEmpty()) {
            return Result.error().message("参数错误");
        }

        for (ShopCar shopCar : shopCars) {
            if (shopCar == null) {
                return Result.error().message("参数错误");
            }
            if (!Objects.equals(shopCar.getUserId(), UserUtils.getUserId())) {
                return Result.error().message("这个购物车 不是你的");
            }
        }
        //前端参数 没有问题后 还需要一些逻辑判断 例如: 是否有未支付的订单
        return userService.createOrder(storeId, shopCars)
                ? Result.ok().message("创建订单成功")
                : Result.error().message("创建订单失败");
    }

//    @AuthorityName(authorityId = 19, authorityName = "用户 查询用户的所有订单")
    @UserAuthority
    @ApiOperation("用户 查询该用户的所有订单")
    @PostMapping(value = {"user/getUserOrderAll/{current}/{limit}", "user/getUserOrderAll"})
    public Result getUserOrderAll(@PathVariable(value = "current", required = false) Integer current,
                                  @PathVariable(value = "limit", required = false) Integer limit,
                                  @RequestBody(required = false) WrapperOrder wrapperOrder) {
        if (wrapperOrder == null) {
            wrapperOrder = new WrapperOrder();
        }
        if (current == null || limit == null) {
            current = 0;
            limit = 10;
        }
        Page<OrderForStoreVo> order = userService.getOrder(current, limit, wrapperOrder);
        // 将状态 转化好
        List<OrderForStoreVo> records = order.getRecords();
        List<OrderForStoreVo> orderForStoreVos = OrderStatus.addStatusString(records);
        return Result.ok()
                .message("查询用户的所有订单成功")
                .data("total", order.getTotal())
                .data("rows", orderForStoreVos);
    }

//    @AuthorityName(authorityId = 20, authorityName = "用户 查询订单详情")
    @UserAuthority
    @ApiOperation("用户 根据订单id 查询订单详情")
    @GetMapping(value = {"user/getOrderDetails/{current}/{limit}/{ofgId}", "user/getOrderDetails/{ofgId}"})
    public Result getOrderDetails(@PathVariable("ofgId") Integer ofgId,
                                  @PathVariable(value = "current", required = false) Integer current,
                                  @PathVariable(value = "limit", required = false) Integer limit
    ) {
        OrderForGoods byId = orderForGoodsService.getById(ofgId);

        if (current == null || limit == null) {
            current = 0;
            limit = 10;
        }

        if (byId == null || !Objects.equals(byId.getUserId(), UserUtils.getUserId())) {
            return Result.error().message("id 错误 无法查询 查询失败");
        }

        Page<OrderForGoodsDetaileVo> page = orderForGoodsDetaileService.getOrderDetailsByOrderId(current, limit, ofgId);
        List<OrderForGoodsDetaileVo> records = page.getRecords();
        List<OrderForGoodsDetaileVo> orderForGoodsDetaileVos = OrderDetailsStatus.addStatusString(records);

        return Result.ok()
                .message("查询用户的订单详情成功").
                data("total", page.getTotal()).
                data("rows", orderForGoodsDetaileVos);
    }


    // 根据订单id 查看 订单详情
    @AuthorityName(authorityId = 21, authorityName = "管理员 根据订单id 查看 订单详情")
    @ApiOperation("管理员 根据订单id 查看 订单详情")
    @GetMapping(value = {"admin/queryOrderDetailsByOrderId/{current}/{limit}/{orderId}", "admin/queryOrderDetailsByOrderId/{orderId}"})
    public Result queryOrderDetailsByOrderId(@PathVariable("orderId") Integer orderId,
                                             @PathVariable(value = "current", required = false) Integer current,
                                             @PathVariable(value = "limit", required = false) Integer limit) {
        if (current == null || limit == null) {
            current = 0;
            limit = 10;
        }
        Page<OrderForGoodsDetaileVo> page = orderForGoodsDetaileService.getOrderDetailsByOrderId(current, limit, orderId);
        List<OrderForGoodsDetaileVo> records = page.getRecords();
        List<OrderForGoodsDetaileVo> orderForGoodsDetaileVos = OrderDetailsStatus.addStatusString(records);
        return Result.ok()
                .message("查询订单详情成功").
                data("total", page.getTotal()).
                data("rows", orderForGoodsDetaileVos);
    }


    //对于订单的条件分页查询
    @AuthorityName(authorityId = 22, authorityName = "管理员 分页条件 查询所有订单")
    @ApiOperation("管理员 分页条件 查询所有订单")
    @PostMapping(value = {"admin/getOrder/{current}/{limit}", "admin/getOrder"})
    public Result getOrder(@PathVariable(value = "current", required = false) Integer current,
                           @PathVariable(value = "limit", required = false) Integer limit,
                           @RequestBody(required = false) WrapperOrder order) {
        if (order == null) {
            order = new WrapperOrder();
        }
        if (current == null || limit == null) {
            current = 0;
            limit = 10;
        }
        Page<OrderForStoreVo> orderForStoreVoPage = orderForGoodsService.queryOrder(current, limit, order);
        List<OrderForStoreVo> orderForStoreVos = OrderStatus.addStatusString(orderForStoreVoPage.getRecords());

        return Result.ok()
                .message("查询成功")
                .data("total", orderForStoreVoPage.getTotal())
                .data("rows", orderForStoreVos);
    }



//    @AuthorityName(authorityId = 23, authorityName = "用户 确认收货")
    @UserAuthority
    @ApiOperation("用户 确认收货")
    @Transactional
    @PostMapping("confirmationOfReceiptForUser/{ofgID}")
    public Result confirmationOfReceiptForUser(@PathVariable("ofgID") Integer ofgID) {
        if (ofgID <= 0) {
            return Result.error();
        }
        return userService.confirmationOfReceiptForUser(ofgID)
                ? Result.ok().message("确认收货成功")
                : Result.error().message("确认收货失败");
    }

//    @AuthorityName(authorityId = 24, authorityName = "用户 取消订单")
    @UserAuthority
    @ApiOperation("用户 取消订单")
    @PostMapping("cancelOrder/{ofgID}")
    @Transactional
    public Result cancelOrder(@PathVariable("ofgID") Integer ofgID) {
        if (ofgID <= 0) {
            return Result.error();
        }
        orderForGoodsService.userCancelOrder(ofgID);
        return Result.ok().message("取消订单成功");
    }


    @AuthorityName(authorityId = 25, authorityName = "管理员 输出今天订单信息详情")
    @ApiOperation("管理员 输出今天订单信息详情")
    @GetMapping("admin/todayOrder/{current}/{limit}")
    public Result getOrderToday(@PathVariable(value = "current", required = false) Integer current,
                                @PathVariable(value = "limit", required = false) Integer limit) {
        if (current == null || limit == null) {
            current = 0;
            limit = 10;
        }
        return orderForGoodsDetaileService.getTodayOrder(current,limit);
    }
}

